package com.gainloop;

import java.util.ArrayList;
import java.util.LinkedList;

import org.alexd.jsonrpc.JSONRPCException;


import android.os.Bundle;
import android.text.Html;
import android.util.Log;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import android.widget.Button;
import android.widget.EditText;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import android.content.Intent;


import com.gainloop.R;
import com.gainloop.Adapters.TagAdapter;
import com.gainloop.Api.ApiResponseArray;
import com.gainloop.Api.Categories;
import com.gainloop.Api.Entity.Category;
import com.gainloop.Api.Entity.User;
import com.gainloop.Data.Registry;
import com.gainloop.Listeners.AutoCompListener;
import com.gainloop.Listeners.CategorySpinnerListener;
import com.gainloop.Listeners.TagsTextWatcher;
import com.gainloop.Listeners.submitNewWishListener;
import com.gainloop.Listeners.tagButtonListener;
import com.gainloop.Utils.ConvertUtils;
import com.gainloop.Utils.HorizontalListView;


public class AddWish extends ActivityAbstract {

	public LinkedList<String> _addedTags ;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_wish);
        
        initHeader();
		headerTitle.setText(R.string.new_wish);
		
        bindCategoriesSpinner();
        
        addDescriptionStart();
        
        bindTags();
        
        EditText gainDesc = (EditText) findViewById(R.id.add_gain_description);
        Button submitButton = (Button) findViewById(R.id.submit); 
        TextView username=(TextView)findViewById(R.id.newWishUsername); 
        username.setText(Registry.GetUser().getName());        
        //submit section
        submitNewWishListener submitlistener = new submitNewWishListener(
        		gainDesc,getIntent(),getApplicationContext(),_addedTags);
        
        submitButton.setOnClickListener(submitlistener);
    }
    
    /**
     * Binding the Tags to the AutoComplete view.
     * @param _addedTags2 
     */
    private void bindTags() {
        AutoCompleteTextView tagsRow = (AutoCompleteTextView) findViewById(R.id.new_gain_autocomplete_tags);
        
        ArrayAdapter<String> tagsAdapter = new ArrayAdapter<String>(this, R.layout.list_item);
        tagsRow.setAdapter(tagsAdapter);
        
        tagsRow.addTextChangedListener(new TagsTextWatcher(tagsAdapter));
        
        //trying to disable SUGGESTIONS - does not seem to work...
        tagsRow.setInputType(EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
        
        Button addTagButton = (Button) findViewById(R.id.new_gain_add_tag_button);
        
        final HorizontalListView addedTagsList = (HorizontalListView) findViewById(R.id.new_gain_added_tag_list); 
        
        _addedTags = new LinkedList<String>();
        
        TagAdapter tagAdapter = new TagAdapter(_addedTags);
        addedTagsList.setAdapter(tagAdapter); 
        
        tagsRow.setOnItemClickListener(new AutoCompListener(_addedTags,tagAdapter,tagsRow));
        
        addedTagsList.setOnItemClickListener(new OnItemClickListener() {
        	//here i will handle the removal of Tags
			@SuppressWarnings("rawtypes")
			@Override
			public void onItemClick(AdapterView parent, View v, int position, long id) {
				Log.v("remove tag in pos=",Integer.toString(position));
				
				_addedTags.remove(position);
				TagAdapter tagAdpter = (TagAdapter) addedTagsList.getAdapter();
				tagAdpter.notifyDataSetChanged();
			}
        }); 
        addTagButton.setOnClickListener(new tagButtonListener(tagsRow,getApplicationContext(),addedTagsList,_addedTags));
        
	}
  
    
    /**
     * Adding the beginning of the Description tab.
     */
	private void addDescriptionStart() {
    	User user=Registry.GetUser();
        TextView gainDescStart = (TextView) findViewById(R.id.add_gain_description_start);
        gainDescStart.setText(Html.fromHtml("<B><FONT COLOR=\"#acd62e\">"+user.getName() +" </B></FONT>"+" wishes to "));
	}
	
	/**
	 * add to the spinner the all Categories from server. 
	 */
	private void bindCategoriesSpinner() {
    	Categories categories = new Categories();
        ApiResponseArray<Category> resp = null;
        try {
			resp = categories.getAll();
		} catch (JSONRPCException e1) {
			e1.printStackTrace();
		}
		ArrayList<Category> allCategories = null;
		if(resp==null){
			declareInternalError();
			Log.v("Categories resp=","null");
			throw new RuntimeException("Could not fatch the Categories");
		}
		allCategories = resp.getData();
		
		String[] allCategoriesStrArr;
		
		Log.v("is allCategories null?=",Boolean.toString(allCategories==null));
		Log.v("return code=",Integer.toString(resp.getReturnCode()));
		
		if(allCategories==null){
			declareInternalError();
			Log.v("Categories fetch","Failed");
			return;
		}
		else{
			Log.v("allCategories size=",Integer.toString(allCategories.size()));
			allCategoriesStrArr = ConvertUtils.transformToStringArray(allCategories);
		}
        
        //adding spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, allCategoriesStrArr);   
        Spinner spinner = (Spinner) findViewById(R.id.category_spinner);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        CategorySpinnerListener spinnerListener = new CategorySpinnerListener(getIntent(),allCategories); 
		spinner.setOnItemSelectedListener(spinnerListener);
		
        
	}
	
	
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		
		MenuItem mi_profile = menu.findItem(R.id.menuProfile);
		mi_profile.setIntent(new Intent(this, Profile.class));
		
		MenuItem mi_home = menu.findItem(R.id.menuHome);
		mi_home.setIntent(new Intent(this, Home.class));
		
		MenuItem mi_search_gain = menu.findItem(R.id.menuSearch); 
		mi_search_gain.setIntent(new Intent(this, GainSearch.class));
		
		MenuItem mi_people = menu.findItem(R.id.menuPeople); 
		mi_people.setIntent(new Intent(this, People.class));
		
		menu.removeItem(R.id.menuNewWish);
		return true;
    }
	
    
	/**
	 * Handling errors softly.
	 */
    private void declareInternalError(){
    	Toast toast = Toast.makeText(AddWish.this, R.string.internal_error, Toast.LENGTH_LONG);
		toast.show();
		
    }
}